package com.smarth.zhizulian.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.gyf.barlibrary.ImmersionBar;
import com.smarth.zhizulian.R;
import com.smarth.zhizulian.adapter.NewsAdapter;
import com.smarth.zhizulian.adapter.VideoAdapter;
import com.smarth.zhizulian.app.BaseActivity;
import com.smarth.zhizulian.app.BaseApplication;
import com.smarth.zhizulian.bean.News;
import com.smarth.zhizulian.bean.Page;
import com.smarth.zhizulian.bean.video.VideoVideoTexts;
import com.smarth.zhizulian.entity.SearchHistory;
import com.smarth.zhizulian.entity.SearchHistoryDao;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.popupwindow.AppDialog;
import com.smarth.zhizulian.utils.KumaToast;
import com.smarth.zhizulian.utils.listhelper.RefreshHelper;
import com.smarth.zhizulian.utils.listhelper.impl.model.HttpListDataModel;
import com.smarth.zhizulian.utils.listhelper.inter.IDataAdapter;
import com.smarth.zhizulian.utils.listhelper.inter.ResponseSender;
import com.smarth.zhizulian.view.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * Created by 18865 on 2018/3/13.
 */

public class SearchActivity extends BaseActivity {
    public static final String INTENT_MODE = "INTENT_MODE";
    public static final int MODE_NEWS = 0;
    public static final int MODE_VIDEO = 1;
    @BindView(R.id.titlebar_back)
    ImageView titlebarBack;
    @BindView(R.id.titlebar_righ)
    TextView titlebarRigh;
    @BindView(R.id.rv_refresh)
    SmartRefreshLayout rvRefresh;
    @BindView(R.id.ll_loadinglayout)
    LoadingLayout llLoadinglayout;
    @BindView(R.id.lv_listview)
    ListView lvListview;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.rv_history)
    RecyclerView rvHistory;
    private int mMode = 0;
    private RefreshHelper refreshHelper;
    private String searchText;
    private BaseQuickAdapter<SearchHistory, BaseViewHolder> historyAdapter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        mMode = getIntent().getIntExtra(INTENT_MODE, MODE_NEWS);
        refreshHelper = new RefreshHelper(mContext, llLoadinglayout, rvRefresh);
        refreshHelper.setDataModel(new HttpListDataModel(mContext) {
            @Override
            public Observable<? extends Page> getObservable(ResponseSender responseSender, int page) {
                rvHistory.setVisibility(View.GONE);
                Observable<? extends Page> observable = mMode == MODE_NEWS
                        ? KumaHttp.getService().articleSearchPage(searchText, page).compose(RxCompos.<Page<News>>getBECompos())
                        : KumaHttp.getService().videoSearchPage(searchText, page).compose(RxCompos.<Page<VideoVideoTexts>>getBECompos());
                return observable;
            }
        });
        refreshHelper.setDataAdapter(mMode == MODE_NEWS ? new MyNewsAdapter(mContext, new ArrayList()) : new VideoAdapter(mContext, new ArrayList(), null) {
            @Override
            public void onGetData(List profitProfits, boolean isRefresh) {
                if (isRefresh) {
                    mDatas.clear();
                }
                mDatas.addAll(profitProfits);
                notifyDataSetChanged();
            }
        });
        List<SearchHistory> sh = getHistory();
        rvHistory.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        historyAdapter = new BaseQuickAdapter<SearchHistory, BaseViewHolder>(R.layout.item_searchhistory, sh) {
            @Override
            protected void convert(final BaseViewHolder helper, final SearchHistory item) {
//                helper.setText(item.getWords())
                helper.setText(R.id.tv_words, item.getWords());
                helper.addOnClickListener(R.id.iv_delete);
            }
        };
        historyAdapter.addHeaderView(LayoutInflater.from(mContext).inflate(R.layout.header_searchhistory, null));
        View view = LayoutInflater.from(mContext).inflate(R.layout.footer_searchhistory, null);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AppDialog(mContext)
                        .setTitle("温馨提示")
                        .setMessage("您确定清空搜索记录吗？")
                        .setOnClickOKListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                BaseApplication.getDaoInstant().getSearchHistoryDao().queryBuilder().where(SearchHistoryDao.Properties.Mode.eq(mMode)).buildDelete().executeDeleteWithoutDetachingEntities();
                                showHistory();
                            }
                        })
                        .setOnClickCancelListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        })
                        .show();
            }
        });
        historyAdapter.addFooterView(view);
        historyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                searchText = ((SearchHistory) adapter.getData().get(position)).getWords();
                etSearch.setText(searchText);
                etSearch.setSelection(searchText.length());
//                refreshHelper.refresh();
                doSearch();
            }
        });
        historyAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                BaseApplication.getDaoInstant().getSearchHistoryDao().delete((SearchHistory) adapter.getData().get(position));
                showHistory();
            }
        });
        historyAdapter.bindToRecyclerView(rvHistory);
        historyAdapter.setEmptyView(R.layout.empty_searchhistory);

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    showHistory();
                }
            }
        });
    }

    @OnClick({R.id.titlebar_back, R.id.titlebar_righ})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titlebar_back:
                this.finish();
                break;
            case R.id.titlebar_righ:
                if (TextUtils.isEmpty(etSearch.getText().toString())) {
                    KumaToast.show(mContext, "请输入关键字");
                    return;
                }
                searchText = etSearch.getText().toString();
                doSearch();
                break;
        }
    }

    public class MyNewsAdapter extends NewsAdapter implements IDataAdapter<List<News>> {

        public MyNewsAdapter(Context context, List<?> datas) {
            super(context, datas);
        }

        @Override
        public void onGetData(List<News> news, boolean isRefresh) {
            if (isRefresh) {
                mDatas.clear();
            }
            mDatas.addAll(news);
            notifyDataSetChanged();

        }

        @Override
        public boolean isDataEmpty() {
            return mDatas == null || mDatas.size() == 0;
        }

        @Override
        public List<News> getMyData() {
            return mDatas;
        }
    }

    public static void open(Context context, int mode) {
        Intent i = new Intent(context, SearchActivity.class);
        i.putExtra(INTENT_MODE, mode);
        context.startActivity(i);
    }

    @Override
    protected void initStatusBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .statusBarColor("#f5f5f5")
                .fitsSystemWindows(true)
                .init();
    }

    private void showHistory() {
        historyAdapter.setNewData(getHistory());
        rvHistory.setVisibility(View.VISIBLE);
    }

    private List<SearchHistory> getHistory() {
        return BaseApplication.getDaoInstant().getSearchHistoryDao().queryBuilder()
                .where(SearchHistoryDao.Properties.Mode.eq(mMode))
                .orderDesc(SearchHistoryDao.Properties.Id)
                .list();
    }

    private void doSearch() {
        try {
            SearchHistory s = BaseApplication.getDaoInstant().getSearchHistoryDao()
                    .queryBuilder()
                    .where(SearchHistoryDao.Properties.Words.eq(searchText), SearchHistoryDao.Properties.Mode.eq(mMode))
                    .unique();
            if (s != null) {
                BaseApplication.getDaoInstant().getSearchHistoryDao().delete(s);
            }
            SearchHistory sh = new SearchHistory();
            sh.setWords(searchText);
            sh.setMode(mMode);
            BaseApplication.getDaoInstant().getSearchHistoryDao().save(sh);
        } catch (Exception e) {
            e.printStackTrace();
        }
        refreshHelper.refresh();
    }
}
